package com.yxwl.demo.ui.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yxwl.demo.utils.Utils;

public abstract class BaseActivity extends AppCompatActivity {

    public Bundle savedInstanceState;
    protected View.OnClickListener onClickListener;

    public View.OnClickListener getOnClickListen() {
        if (onClickListener == null) {
            onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int id = v.getId();
                    widgetClick(v, id);
                }
            };
        }
        return onClickListener;
    }

    protected void widgetClick(View view, int id) {
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {//savedInstanceState意义用法 https://blog.csdn.net/qq_24118527/article/details/82914041
        super.onCreate(savedInstanceState);
        if (isTask()) {
            return;
        }
        if (!isFinishing()) {
            beforeOnCreate();
        }
        if (!isFinishing()) {
            this.savedInstanceState = savedInstanceState;
            setContentView(getLayoutId());
        }

        if (!isFinishing()) {
            init();
        }
        if (!isFinishing()) {
            initView();
        }
        if (!isFinishing()) {
            initData();
        }
        if (!isFinishing()) {
            initListen();
        }
        if (!isFinishing()) {
            afterInit();
        }
    }

    public boolean isTask() {
        return isTask(this);
    }

    public boolean isTask(Activity activity) {
        if (!activity.isTaskRoot()) {
            Intent intent = activity.getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
                activity.finish();
                return true;
            }
        }
        return false;
    }

    protected void beforeOnCreate() {
    }

    protected void init() {
    }

    protected void initView() {
    }

    protected void initData() {
    }

    protected void initListen() {
    }

    protected void afterInit() {
    }

    protected int getLayoutId() {
        return -1;
    }


    public void startAct(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(Utils.getContext(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//兼容
        Utils.getContext().startActivity(intent);
    }
}
